package com.ssc.portal.www.ice;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import TransferManage.TransferInterfacePrx;
import TransferManage.TransferInterfacePrxHelper;

import com.ssc.portal.common.utils.AppConfig;

@Component
public class ClientIntegration {
	
	private String CLIENTPATH = "com/ssc/portal/www/ice/config.client";
	
	
	
	private TransferInterfacePrx transferInterfacePrx;
	private IceClient iceClient;
	
	private Logger logger = Logger.getLogger(ClientIntegration.class);

	public void initIceClient() {
		String objKey = AppConfig.getProperty("serverIce.objKey");
		int count = 0;

		while (true) {
			try {
				iceClient = new IceClient();

				Map<String, Class> prxHelperMap = new HashMap<String, Class>();
				prxHelperMap.put("TransferInterfacePrxHelper", TransferInterfacePrxHelper.class);

				iceClient.initClientPrxs(CLIENTPATH, prxHelperMap);
				transferInterfacePrx = (TransferInterfacePrx) iceClient.getPrxByKey("TransferInterfacePrxHelper");
				logger.info("ICE客户端创建成功");
				break;
			} catch (Exception e) {
				e.printStackTrace();
				if (++count == 1) {
					logger.fatal("抓取节点初始化数据中心的ICE服务端，正在等待节点管理中心启动ICE服务...");
				}
				try {
					Thread.sleep(1000L * 5);
				} catch (Exception e2) {
				}
			}
		}
	}
	
	public String betting(String bets){
		return  transferInterfacePrx.betting(bets);
	}

/*	*//**
	 * 节点注册
	 * 
	 * @param nodeRegisterInput
	 *            节点注册请求报文对象
	 *//*
	public void nodeRegister(NodeRegisterInput nodeRegisterInput) {
		try {
			// nodeRegisterInput.setIp(SystemUtil.getLocalIP());

			xs.alias("NodeRegisterInput", NodeRegisterInput.class);
			xs.alias("Config", MoreAccountConfig.class);
			xs.alias("LoginThirdAccount", LoginThirdAccount.class);
			xs.alias("Proxy", Proxy.class);

			StringWriter sw = new StringWriter();
			xs.toXML(nodeRegisterInput, sw);

			String reqStr = nodeManageZreocSrvIPrx.nodeRegister(sw.toString());// 响应报文

			StringReader stringReader = new StringReader(reqStr);
			NodeRegisterOutput nodeRegisterOutput = new NodeRegisterOutput();
			xs.alias("NodeRegisterOutput", NodeRegisterOutput.class);
			xs.fromXML(stringReader, nodeRegisterOutput);

			if (nodeRegisterOutput.getStatus() == 0) {// 失败
				// SystemData.setHasError(true);// 节点注册失败时,设置是否存在错误的标识为true
				logger.info(nodeRegisterOutput.getRemark());// 将失败的原因写入错误日志文件
			}
		} catch (Exception e) {
			logger.error("向管理中心注册当前节点出现异常：" + e.toString() + "，稍后(30s)重试...");
		}
	}

	*//**
	 * 心跳
	 * 
	 * @param heartbeatInput
	 *            心跳接口请求报文对象
	 *//*
	public void heartbeat(HeartbeatInput heartbeatInput) {
		String reqXml = null;
		try {
			xs.alias("HeartbeatInput", HeartbeatInput.class);
			xs.alias("SnatchItemStatus", SnatchItemStatus.class);

			StringWriter sw = new StringWriter();
			xs.toXML(heartbeatInput, sw);

			reqXml = sw.toString();
			
			String returnXml = nodeManageZreocSrvIPrx.heartbeat(reqXml);
			logger.debug("发送心跳报文：\n" + reqXml);
			
			StringReader stringReader = new StringReader(returnXml);
			HeartbeatOutput heartbeatOutput = new HeartbeatOutput();
			xs.alias("HeartbeatOutput", HeartbeatOutput.class);
			xs.fromXML(stringReader, heartbeatOutput);
			
			if (heartbeatOutput.getStatus() == 0) {// 失败
				logger.info(heartbeatOutput.getRemark());
				this.nodeRegister(SystemData.nodeConfigs);
			}
		} catch (Exception e) {
			if (e instanceof Ice.SocketException) {
				synchronized (this.iceClient) {
					logger.error("ICE连接中断，正在试图重连...");
					this.iceClient.setAvailable(false);
					this.initIceClient();
					this.nodeRegister(SystemData.nodeConfigs);
					try {
						this.iceClient.wait(1000L);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
				// 重新调用服务
				if (iceClient.isAvailable()) {
					nodeManageZreocSrvIPrx.heartbeat(reqXml);
				} else {
					// 记录错误报文日志，不再处理此报文
					logger.error("ICE连接中断，重试失败，放弃本次接口调用，本次要发送的心跳报文为:" + reqXml, e);
				}
			} else if (e instanceof Ice.TimeoutException) {
				logger.error("ICE连接操作超时，放弃本次接口调用，本次要发送的心跳报文为:" + reqXml, e);
			} else {
				logger.error("ICE连接中断，发送其他错误，本次要发送的心跳报文为:" + reqXml, e);
				this.nodeRegister(SystemData.nodeConfigs);
			}
			
		}
	}

	*//**
	 * 发送抓取数据
	 * 
	 * @param onlyCode
	 * @param ratioDataInput
	 * @return
	 *//*
	public String ratioDataInput(RatioDataInput ratioDataInput) {
		long time1 = System.currentTimeMillis();
		String thirdSystem = ratioDataInput.getThirdSystem();
		String snatchItem = ratioDataInput.getSnatchItem();

		String sendXml = SystemUtil.createRatioXml(ratioDataInput);
		
		System.out.println("賠率發管理中心時間A："+(System.currentTimeMillis()-time1));
		time1 = System.currentTimeMillis();
		SnatchLog.log(thirdSystem, snatchItem, sendXml);
		
		// 压缩有效报文
		sendXml = SystemUtil.gZip(sendXml);
		System.out.println("賠率發管理中心時間B："+(System.currentTimeMillis()-time1));
		time1 = System.currentTimeMillis();
		// 附加报文前缀(格式:抓取项id;序列码;抓取耗时;压缩后的赔率数据报文)
		StringBuilder sbd = new StringBuilder(thirdSystem + "_" + snatchItem).append(";").append(ratioDataInput.getSeqNum()).append(";").append(ratioDataInput.getSnatchCost()).append(";").append(sendXml);

		String retXml = null;
		try {
			retXml = nodeManageZreocSrvIPrx.ratioDataInput(sbd.toString());
		} catch (Exception e) {
			if (e instanceof Ice.SocketException) {
				synchronized (this.iceClient) {
					logger.error("ICE连接中断，正在试图重连...");
					this.iceClient.setAvailable(false);
					this.initIceClient();
					this.nodeRegister(SystemData.nodeConfigs);
					try {
						this.iceClient.wait(1000L);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
				// 重新调用服务
				if (iceClient.isAvailable()) {
					retXml = nodeManageZreocSrvIPrx.ratioDataInput(sbd.toString());
				} else {
					// 记录错误报文日志，不再处理此报文
					logger.error("ICE连接中断，重试失败，放弃本次接口调用，本次要发送的赔率数据报文为:" + sbd.toString(), e);
				}
			} else if (e instanceof Ice.TimeoutException) {
				logger.error("ICE连接操作超时，放弃本次接口调用，本次要发送的赔率数据报文为:" + sbd.toString(), e);
			} else {
				logger.error("ICE连接中断，发送其他错误，本次要发送的赔率数据报文为:" + sbd.toString(), e);
			}
		}
		SnatchLog.log(thirdSystem, snatchItem, retXml);
		System.out.println("賠率發管理中心時間C："+(System.currentTimeMillis()-time1));
		time1 = System.currentTimeMillis();
		return retXml;
	}

	*//**
	 * 发送盘中信息
	 * 
	 * @param matchInfoDataInput
	 * @return
	 *//*
	public String matchInfoDataInput(MatchInfoDataInput matchInfoDataInput) {
		String thirdSystem = matchInfoDataInput.getThirdSystem();
		
		String sendXml = SystemUtil.createMatchInfoXml(matchInfoDataInput);
		
		SnatchLog.logLive(thirdSystem, sendXml);
		
		// 附加报文前缀(格式:抓取项id;序列码;盘中信息报文)
		StringBuilder sbd = new StringBuilder(thirdSystem + "_" + matchInfoDataInput.getSnatchItem()).append(";").append(matchInfoDataInput.getSeqNum()).append(";").append(sendXml);

		String retXml = null;
		try {
			retXml = nodeManageZreocSrvIPrx.matchInfoData(sbd.toString());
		} catch (Exception e) {
			if (e instanceof Ice.SocketException) {
				synchronized (this.iceClient) {
					logger.error("ICE连接中断，正在试图重连...");
					this.iceClient.setAvailable(false);
					this.initIceClient();
					this.nodeRegister(SystemData.nodeConfigs);
					try {
						this.iceClient.wait(1000L);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
				// 重新调用服务
				if (iceClient.isAvailable()) {
					retXml = nodeManageZreocSrvIPrx.matchInfoData(sbd.toString());
				} else {
					// 记录错误报文日志，不再处理此报文
					logger.error("ICE连接中断，重试失败，放弃本次接口调用，本次要发送的盘中信息报文为:" + sbd.toString(), e);
				}
			} else if (e instanceof Ice.TimeoutException) {
				logger.error("ICE连接操作超时，放弃本次接口调用，本次要发送的盘中信息报文为:" + sbd.toString(), e);
			} else {
				logger.error("ICE连接中断，发送其他错误，本次要发送的盘中信息报文为:" + sbd.toString(), e);
			}
		}
		
		SnatchLog.logLive(thirdSystem, retXml);

		return retXml;
	}

	*//**
	 * 发送报错信息
	 * 
	 * @param errorInput
	 * @return
	 *//*
	public String error(ErrorInput errorInput) {
		String itemID = SystemUtil.getItemID(errorInput.getThirdSystem(), errorInput.getSnatchItem());

		if (errorInput.isExit()) {// 抓取数据时,登录用户被第三方系统踢出
			LoginThread loginThread = SystemData.loginItemStatus.get(itemID);
			if (null != loginThread) {
				SnatchThread snatchThread = SystemData.snatchItemStatus.get(itemID);
				if (null != snatchThread) {
					snatchThread.destroy();// 销毁该抓取线程
					SystemData.snatchItemStatus.remove(itemID, snatchThread);// 将相应的抓取线程停止
				}
				loginThread.flag = false;// 将登录线程状态置为false
				SystemData.loginItemStatus.remove(itemID, loginThread);// 将相应的登录线程停止
			}
		}

		StringWriter sw = new StringWriter();
		xs.toXML(errorInput, sw);

		String reqXml = sw.toString();
		String respXml = null;
		try {
			respXml = nodeManageZreocSrvIPrx.error(reqXml);
		} catch (Exception e) {
			if (e instanceof Ice.SocketException) {
				synchronized (this.iceClient) {
					logger.error("ICE连接中断，正在试图重连...");
					this.iceClient.setAvailable(false);
					this.initIceClient();
					this.nodeRegister(SystemData.nodeConfigs);
					try {
						this.iceClient.wait(1000L);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
				// 重新调用服务
				if (iceClient.isAvailable()) {
					respXml = nodeManageZreocSrvIPrx.error(reqXml);
				} else {
					// 记录错误报文日志，不再处理此报文
					logger.error("ICE连接中断，重试失败，放弃本次接口调用，本次要发送的错误信息报文为:" + reqXml, e);
				}
			} else if (e instanceof Ice.TimeoutException) {
				logger.error("ICE连接操作超时，放弃本次接口调用，本次要发送的错误信息报文为:" + reqXml, e);
			} else {
				logger.error("ICE连接中断，发送其他错误，本次要发送的错误信息报文为:" + reqXml, e);
			}
		}
		return respXml;
	}

	*//**
	 * 发送验证码
	 * 
	 * @param validateCodeInput
	 * @return
	 *//*
	public ValidateCodeOutput validateCode(ValidateCodeInput validateCodeInput) {

		StringWriter sw = new StringWriter();
		xs.toXML(validateCodeInput, sw);

		String respStr = null;
		String reqStr = sw.toString();
		try {
			respStr = nodeManageZreocSrvIPrx.validateCode(reqStr);
		} catch (Exception e) {
			if (e instanceof Ice.SocketException) {
				synchronized (this.iceClient) {
					logger.error("ICE连接中断，正在试图重连...");
					this.iceClient.setAvailable(false);
					this.initIceClient();
					this.nodeRegister(SystemData.nodeConfigs);
					try {
						this.iceClient.wait(1000L);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
				// 重新调用服务
				if (iceClient.isAvailable()) {
					respStr = nodeManageZreocSrvIPrx.validateCode(reqStr);
				} else {
					// 记录错误报文日志，不再处理此报文
					logger.error("ICE连接中断，重试失败，放弃本次接口调用，本次要发送的验证码报文为:" + reqStr, e);
				}
			} else if (e instanceof Ice.TimeoutException) {
				logger.error("ICE连接操作超时，放弃本次接口调用，本次要发送的验证码报文为:" + reqStr, e);
			} else {
				logger.error("ICE连接中断，发送其他错误，本次要发送的验证码报文为:" + reqStr, e);
			}
		}
		
		ValidateCodeOutput validateCodeOutput = new ValidateCodeOutput();

		return (ValidateCodeOutput) xs.fromXML(respStr, validateCodeOutput);
	}
*/

	/**
	 * 销毁ICE客户端
	 */
	public void destoryIceClient() {
		iceClient.destoryProxy();
	}

}
